package com.yusvn.scm.goods.base.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.constant.Const;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.ScmPzbhmx;

import java.util.List;

public class ScmPzbhmxService extends BaseService {

         ScmPzbhmx dao = new ScmPzbhmx().dao();

    public Page<ScmPzbhmx> selectPzbhList(Kv kv){

        Page<ScmPzbhmx> pzbhList = dao.template("scmPzbhmx.page",kv).paginate(getPage(kv),getLimit(kv));
        return pzbhList;
    }

    public RetKit addPzbhmx(String jsonObj){

        ScmPzbhmx scmPzbhmx = JSON.parseObject(jsonObj,ScmPzbhmx.class);
        System.out.println("scmPzbhmx"+scmPzbhmx);
        long id = Db.use(Const.SCMDB).queryLong("select nvl(max(id),0)+1 cnt from scm_pzbhmx ");
        scmPzbhmx.setId(id); //查询最大ID oracle不支持自增ID
        if (scmPzbhmx.use(Const.SCMDB).save()){
            return RetKit.ok("新增成功");
        }
        return RetKit.fail("新增失败");
    }

    public RetKit updatePzbhmx(String jsonObj){

        ScmPzbhmx scmPzbhmx = JSON.parseObject(jsonObj,ScmPzbhmx.class);
        if (scmPzbhmx.use(Const.SCMDB).update()){
            return RetKit.ok("修改成功");
        }
        return RetKit.fail("修改失败");
    }

    public RetKit deletePzbhmx(String id){


        if (dao.deleteById(id)){
            return RetKit.ok("删除成功");
        }
        return RetKit.fail("删除失败");
    }

    public RetKit deleteBatch(String idsStr){
        JSONObject idsObj = JSON.parseObject(idsStr);
        JSONArray idsArr = idsObj.getJSONArray("ids");

        Object[][] paras = new Object[idsArr.size()][1];
        for(int i=0;i<idsArr.size();i++) {
            paras[i][0] = idsArr.get(i);
        }

        int[] cntArr = Db.use(Const.SCMDB).batch("delete from scm_pzbhmx where id=? ", paras, 100);

        //统计成功行数
        int cntOk = 0;
        for(int i=0; i<cntArr.length; i++) {
            if(cntArr[i]==-2 || cntArr[i]==1) { //oracle返回-2、sqlserver返回1，表示成功
                cntOk++;
            }
        }

        if(cntArr.length>0) {
            return RetKit.ok("成功删除 "+cntOk+" 条数据");
        }

        return RetKit.fail("批量删除失败");
    }

    public List<Record> selectAll(Kv kv){

        String mid = kv.getStr("mid");
        List<Record> records = Db.use(Const.SCMDB).find("select * from scm_pzbhmx where mid=?",mid);
        return records;
    }

}
